package com.example.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @ClassName DistributeServer
 * @Author 小坏
 * @Date 2021/8/20、16:06
 * @Version 1.0
 */
public class DistributeServer {

    private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zKeeper;


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        //获取zk连接
        DistributeServer server = new DistributeServer();
        server.getConnect();

        //注册服务器到zk集群
        server.regist(args[0]);

        //启动业务逻辑
        server.business();
    }

    private void business() throws InterruptedException {
        //休眠一会
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws KeeperException, InterruptedException {
        String s = zKeeper.create("/servers/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + "is online");
    }


    //创建连接
    private void getConnect() throws IOException {
        zKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }
}
